<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import useAttractionsStore from '@/store/attractions/index.js'
import router from '@/router/index.js'
import { AiEditor } from "aieditor"
import "aieditor/dist/style.css"
import { onMounted, onUnmounted, reactive, ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { UploadProps } from 'element-plus'
import useLoginStore from '@/store/user/index.js'

const attractionsStore = useAttractionsStore()
const imageUrl = ref('')
const videoUrl = ref('')
const isEdit = ref(false)
const formData = reactive({
  scenicName: '',
  scenicAddress: '',
  scenicPic: '',
  status: 1,
  scenicType: '',
  scenicVideo: '',
  ticketPrice: '',
  contractPhone: '',
  scenicText: '',
  openTime: '',
  closeTime: ''
})
const divRef = ref()
let aiEditor = null
const loginStore = useLoginStore()
const scienceId = router.currentRoute._rawValue.query.id;
// 初始化页面，加载数据（修改时）
onMounted(async () => {
    console.log('传过来的id是',router.currentRoute._rawValue.query.id)

    if (scienceId != null) {
        try {
            console.log('我进来了')
            isEdit.value = true;
            console.log('isEdit', isEdit)
            const details = await attractionsStore.getAttractionDetail(scienceId);
            console.log('details', details.data)
            if (details.data) {
                Object.assign(formData, details.data);
                imageUrl.value = details.data.scenicPic;
                videoUrl.value = details.data.scenicVideo;
            }
            console.log('formData', formData)
        } catch (error) {
            ElMessage.error("加载景点详情失败");
        }
    }
    aiEditor = new AiEditor({
      element: divRef.value,
      placeholder: "点击输入景点详情介绍...",
      onChange: (editor) => {
        formData.scenicText = editor.getHtml()
      }
    })
  // 如果是编辑模式，设置富文本框的初始内容
  if (isEdit.value && formData.scenicText) {
    aiEditor.setContent(formData.scenicText);
  }
});

// 提交表单
const submitForm = async () => {
      if (scienceId != null) {
          console.log('开始修改了')
          // 修改景点
          const res = await attractionsStore.updateAttraction(formData);
          console.log('修改结果', res);
          if (res.code !== 1) {
            ElMessage.error(res.msg);
          }else {
            router.push("/main/system/attractions");
            ElMessage.success("修改成功");
          }
      } else {
          // 新增景点
        const res =  await attractionsStore.addAttractions(formData);
        if (res.code !== 1) {
          ElMessage.error(res.msg);
        }else {
          router.push("/main/system/attractions");
          ElMessage.success("添加成功");
        }
      }
};
//对回传的图片或者视频做处理
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  console.log('上传的文件信息如下:',uploadFile);
  // 判断文件类型，并根据类型分别赋值
  if (response.data.type === "1") {
    // 如果是图片
    formData.scenicPic = response.data.url; // 将返回的图片路径赋值给 scenicPic
    imageUrl.value = response.data.url;
    //imageUrl.value = URL.createObjectURL(uploadFile.raw!); // 预览图片
    console.log('完整的路径如下:',imageUrl.value);
  } else if (response.data.type === "2") {
    // 如果是视频
    formData.scenicVideo = response.data.url; // 将返回的视频路径赋值给 scenicVideo
    videoUrl.value = response.data.url;
    console.log('完整的路径如下:',videoUrl.value);
    //videoUrl.value = URL.createObjectURL(uploadFile.raw!); // 预览视频
  }

}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  console.log('上传的文件信息如下:',rawFile);
  console.log('上传的文件类型信息如下:',rawFile.type);
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'video/mp4') {
    ElMessage.error('只能上传对应格式文件')
    return false
  }
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB')
    return false
  }
  return true
}
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
// 添加表单校验规则
const formRules = {
  scenicName: [
    { required: true, message: '请输入景点名称', trigger: 'blur' }
  ],
  scenicType: [
    { required: true, message: '请选择景点类型', trigger: 'change' }
  ],
  ticketPrice: [
    { required: true, message: '请输入门票价格', trigger: 'blur' }
  ],
  contractPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' }
  ],
  openTime: [
    { required: true, message: '请选择开放时间', trigger: 'change' }
  ],
  closeTime: [
    { required: true, message: '请选择关闭时间', trigger: 'change' }
  ],
  scenicAddress: [
    { required: true, message: '请输入景点地址', trigger: 'blur' }
  ],
  scenicPic: [
    { required: true, message: '请上传景点图片', trigger: 'change' }
  ],
  scenicText: [
    { required: true, message: '请输入景点介绍', trigger: 'blur' }
  ]
};
</script>

<template>
  <div class="add-container">
    <h2 class="title">{{ isEdit ? '修改景点信息' : '新增景点' }}</h2>
    <el-alert
      v-if="isEdit"
      title="当前为修改操作，请确认信息后提交"
      type="info"
      show-icon
      class="mb-4"
    />
    <el-form :model="formData" :rules="formRules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="景点名称" prop="scenicName">
            <el-input v-model="formData.scenicName" placeholder="请输入景点名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="景点类型" prop="scenicType">
            <el-select v-model="formData.scenicType" placeholder="请选择景点类型" style="width: 100%">
              <el-option label="自然景观" value="自然景观" />
              <el-option label="人文景观" value="人文景观" />
              <el-option label="历史遗迹" value="历史遗迹" />
              <el-option label="主题公园" value="主题公园" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="门票价格" prop="ticketPrice">
            <el-input-number
              v-model="formData.ticketPrice"
              :min="0"
              :precision="2"
              :step="10"
              style="width: 100%"
              placeholder="请输入门票价格"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="contractPhone">
            <el-input v-model="formData.contractPhone" placeholder="请输入联系电话"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开放时间" prop="openTime">
            <el-time-picker
              v-model="formData.openTime"
              format="HH:mm"
              value-format="HH:mm"
              placeholder="选择开放时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关闭时间" prop="closeTime">
            <el-time-picker
              v-model="formData.closeTime"
              format="HH:mm"
              value-format="HH:mm"
              placeholder="选择关闭时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>


      <el-form-item label="景点地址" prop="scenicAddress">
        <el-input v-model="formData.scenicAddress" placeholder="请输入详细地址"/>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="景点图片" prop="scenicPic">
            <el-upload
              class="avatar-uploader"
              action="/api/attractions/upload"
              :show-file-list="false"
              :headers="{ token: loginStore.token }"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              <template #tip>
                <div class="el-upload__tip">只能上传jpg/png文件</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="景点视频" prop="scenicVideo">
            <el-upload
              class="avatar-uploader"
              action="/api/attractions/upload"
              :show-file-list="false"
              :headers="{ token: loginStore.token }"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
            >
              <video v-if="videoUrl" :src="videoUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              <template #tip>
                <div class="el-upload__tip">支持mp4格式视频</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="开放状态">
        <el-switch
          v-model="formData.status"
          :active-value="1"
          :inactive-value="0"
          active-text="开放"
          inactive-text="关闭"
        />
      </el-form-item>

      <el-form-item label="景点介绍" prop="scenicText">
        <div ref="divRef" style="height: 400px; border: 1px solid #dcdfe6; border-radius: 4px;"/>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="router.back()">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped lang="less">
.add-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;

  .el-form {
    max-width: 1000px;
    margin: 0 auto;
  }

  :deep(.el-upload-list) {
    width: 100%;
  }

  :deep(.el-upload) {
    width: 100%;
    .el-button {
      width: 100%;
    }
  }

  .el-upload__tip {
    color: #909399;
    font-size: 12px;
    margin-top: 4px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.title {
   text-align: center; /* 居中显示 */
   font-size: 24px; /* 设置字体大小 */
   font-weight: bold; /* 加粗字体 */
   color: #409EFF; /* 设置字体颜色 */
   margin-bottom: 20px; /* 设置底部间距 */
   padding: 20px 0; /* 设置上下内边距 */
   background-color: #f5f7fa; /* 设置背景颜色 */
   border-radius: 8px; /* 圆角效果 */
   box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
 }

</style>
